package model.search;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

public class RegReplace {
	private class Rule {
		private String lookFor;
		private String replaceWith;
		public Rule(String lookFor, String replaceWith) {
			this.lookFor = lookFor;
			this.replaceWith = replaceWith;
		}
		public String getLookFor() {
			return lookFor;
		}
		public String getReplaceWith() {
			return replaceWith;
		}
		
	}

	private ArrayList<Rule> rules;

	private String file = model.MainModel.applicationRoot
			+ "/settings/regreplace.txt";
	
	public RegReplace() {
		rules = new ArrayList<Rule>();
		load();
	}

	public RegReplace(String file) {
		rules = new ArrayList<Rule>();
		this.file = file;
		if (file != "")
			load();
	}

	private void load() {
		FileReader fr;
		try {
			fr = new FileReader(new File(file));
			BufferedReader br = new BufferedReader(fr);
			while (br.ready()) {
				String rule = br.readLine();
				addRuleString(rule);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Boolean addRuleString(String rule) {
		try {
			String[] parts = rule.split("=");
			String lookFor = getValue(parts[0]);
			String replaceWith = getValue(parts[1]);
			rules.add(new Rule(lookFor, replaceWith));
			return true;
		} catch (IndexOutOfBoundsException e) {
			return false;
		}
	}

	private String getValue(String string) throws IndexOutOfBoundsException {
		string = string.trim();
		if (!(string.startsWith("\"") && string.endsWith("\"") && string.length() > 1))
			throw new IndexOutOfBoundsException();
		String result = "";
		for (int i = 1; i < string.length() - 1; i++)
			result += string.charAt(i);
		return result;
	}

	public String manipulate(String string) {
		for (Rule rule : rules)
			string = string.replaceAll(rule.getLookFor(), rule.getReplaceWith());
		return string;
	}
}
